<!-- Add Template -->
<template>
  <el-dialog :visible.sync="dialogStatus"
             width="700px"
             append-to-body
             destroy-on-close
             @close="closeBefore">
    <div slot="title"
         style="fontSize:1.2em;fontWeight:bold;color:#333;">
      <template v-if="dialogType === 'add'">
        {{ $t('custom.workSchedule.template.addTemplate') }}
      </template>
      <template v-else-if="dialogType === 'edit'">
        {{ $t('custom.workSchedule.template.editTemplate') }}
      </template>
    </div>
    <div>
      <el-form :rules="formRules"
               ref="template-form"
               :model="templateForm">
        <el-form-item style="margin-bottom:5px;"
                      prop="templateName">
          <el-row :gutter="20"
                  style="display:flex;align-items:center;margin-bottom:10px;">
            <el-col :span="6"
                    style="text-align:right;">{{ $t('custom.workSchedule.templateName') }}</el-col>
            <el-col :span="18">
              <el-input v-model="templateForm.templateName"
                        :placeholder="$t('custom.workSchedule.inputTemplateName')"></el-input>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item style="margin-bottom:5px;"
                      prop="selectedTimezone">
          <el-row :gutter="24"
                  style="display:flex;align-items:center;margin-bottom:10px;">
            <el-col :span="6"
                    style="text-align:right;">{{ $t('custom.workSchedule.timezoneTitle') }}</el-col>
            <el-col :span="14">
              <el-select v-model="templateForm.selectedTimezone"
                         style="width:100%;height:30px;"
                         :filterable="true"
                         :default-first-option="true"
                         :placeholder="$t('custom.workSchedule.selectTimezone')">
                <el-option v-for="item in timezoneListData"
                           :key="item"
                           :label="item"
                           :value="item">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-tag v-show="templateForm.selectedTimezone">{{'UTC'+computedTimeOffset(templateForm.selectedTimezone)}}</el-tag>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
        <el-row :gutter="20"
              style="height:30px;line-height:30px;fontWeight:bold;">
        <el-col :span="6"
                style="text-align:right;">{{ $t('custom.workSchedule.templatetime')}}</el-col>
        <el-col :span="9"
                style="text-align:center;">{{ $t('custom.workSchedule.from') }}</el-col>
        <el-col :span="9"
                style="text-align:center;">{{ $t('custom.workSchedule.to') }}</el-col>
      </el-row>
      <el-row :gutter="20"
              style="display:flex;align-items:center;margin-bottom:15px;">
        <el-col :span="6"></el-col>
        <el-col :span="9">
          <el-time-picker v-model="templateBeginTime"
                          size="small"
                          style="width:80%;"
                          @change="csetBeginTime"
                          @focus="setBeginTime"
                          format="HH:mm"
                          value-format="HH:mm"
                          :picker-options="{
                            selectableRange: `00:00:00 - ${templateEndTime?templateEndTime+':00':'23:59:59'}`
                          }"
                          :placeholder="$t('custom.workSchedule.from')">
          </el-time-picker>
        </el-col>
        <el-col :span="9">
          <el-time-picker v-model="templateEndTime"
                          size="small"
                          style="width:80%;"
                          format="HH:mm"
                          @focus="setEndTime"
                          :picker-options="{
                            selectableRange: `${templateBeginTime?templateBeginTime+':00':'00:00:00'} - 23:59:59`
                          }"
                          value-format="HH:mm"
                          :placeholder="$t('custom.workSchedule.to')">
          </el-time-picker>
        </el-col>
      </el-row>
      <el-row :gutter="20"
              style="height:30px;line-height:30px;fontWeight:bold;">
        <el-col :span="6"
                style="text-align:right;">{{ $t('custom.workSchedule.day') }}</el-col>
      </el-row>

      <el-row v-for="(item,index) in scheduleData"
              :key="index"
              :gutter="20"
              style="display:flex;align-items:center;margin-bottom:15px;">
        <el-col :span="6"
                style="text-align:right;">{{ item.dayOfWeek }}</el-col>
        <el-col :span="9">
          <el-time-picker v-model="item.beginTime"
                          size="small"
                          style="width:80%;"
                          format="HH:mm"
                          :picker-options="{
                            selectableRange: `00:00:00 - ${item.endTime?item.endTime+':00':'23:59:59'}`
                          }"
                          @focus="setItemBeginTime(item)"
                          value-format="HH:mm"
                          :placeholder="$t('custom.workSchedule.from')">
          </el-time-picker>
        </el-col>
        <el-col :span="9">
          <el-time-picker v-model="item.endTime"
                          size="small"
                          style="width:80%;"
                          format="HH:mm"
                          :picker-options="{
                              selectableRange: `${item.beginTime?item.beginTime+':00':'00:00:00'} - 23:59:59`
                            }"
                          @focus="setItemEndTime(item)"
                          value-format="HH:mm"
                          :placeholder="$t('custom.workSchedule.to')">
          </el-time-picker>
          <el-tooltip effect="dark"  :open-delay="1000" placement="top"  content="Schedule Unify">
              <i class="cuifont icon_schedule_unify" style="margin-left: 10px;" @click="setTemplateTime(item)"></i>
          </el-tooltip>
        </el-col>
      </el-row>
    </div>
    <div slot="footer">
      <el-button size="mini"
                 style="color:#999;fontWeight:bold;"
                 @click="closeDialog">{{ $t('custom.workSchedule.cancel') }}</el-button>
      <el-button size="mini"
                 type="primary"
                 style="fontWeight:bold;"
                 :loading="saveLoading"
                 @click="saveTemplate">{{ $t('custom.workSchedule.confirm') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import moment from 'moment'
import { TimeZoneNameList } from '@/utils'
export default {
  data () {
    return {
      params: {
        startTime: '08:00',
        endTime: '18:00'
      },
      templateId: null,
      dialogType: null,
      dialogStatus: false,
      timezoneListData: TimeZoneNameList(),
      scheduleData: [
        {
          'dayOfWeek': 'MONDAY',
          'beginTime': '',
          'endTime': '',
          'sort': 1
        },
        {
          'dayOfWeek': 'TUESDAY',
          'beginTime': '',
          'endTime': '',
          'sort': 2
        },
        {
          'dayOfWeek': 'WEDNESDAY',
          'beginTime': '',
          'endTime': '',
          'sort': 3
        },
        {
          'dayOfWeek': 'THURSDAY',
          'beginTime': '',
          'endTime': '',
          'sort': 4
        },
        {
          'dayOfWeek': 'FRIDAY',
          'beginTime': '',
          'endTime': '',
          'sort': 5
        },
        {
          'dayOfWeek': 'SATURDAY',
          'beginTime': '',
          'endTime': '',
          'sort': 6
        },
        {
          'dayOfWeek': 'SUNDAY',
          'beginTime': '',
          'endTime': '',
          'sort': 7
        }
      ],
      saveLoading: false,
      templateForm: {
        templateName: null,
        selectedTimezone: this.$store.state.user.tenantTimezoneId
      },
      formRules: {
        templateName: [
          { required: true, message: ' ', trigger: 'blur' }
        ],
        selectedTimezone: [
          { required: true, message: ' ', trigger: 'blur' }
        ]
      },
      templateBeginTime: '08:00',
      templateEndTime: '17:00'
    }
  },
  methods: {
    computedTimeOffset (data) {
      try {
        if (data) {
          return moment.tz(data).format('Z')
        }
      } catch (error) {
        return ''
      }
    },
    getTemplateInfo (id) {
      this.$interface.schedule.getTemplateInfoApi(id)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          let resultData = res.data
          this.templateId = resultData.id
          this.templateForm.templateName = resultData.name
          this.templateForm.selectedTimezone = JSON.parse(resultData.template).timezone
          this.scheduleData = JSON.parse(resultData.template).scheduleData
        })
        .catch(() => { })
    },
    setTemplateTime (data) {
      data.beginTime = this.templateBeginTime
      data.endTime = this.templateEndTime
      this.$forceUpdate()
    },
    setBeginTime () {
      !this.templateBeginTime && (this.templateBeginTime = '00:00')
    },
    csetBeginTime (val) {
    },
    setEndTime () {
      !this.templateEndTime && (this.templateEndTime = '00:00')
    },
    setItemBeginTime (data) {
      !data.beginTime && (data.beginTime = '00:00')
    },
    setItemEndTime (data) {
      !data.endTime && (data.endTime = '00:00')
    },
    saveTemplate () {
      this.verifyNameAndTimezone()
        .then(() => {
          this.saveLoading = true
          const params = {
            name: this.templateForm.templateName,
            type: 'work_schedule',
            template: JSON.stringify({
              timezone: this.templateForm.selectedTimezone,
              scheduleData: this.scheduleData
            })
          }
          this.templateId && (params.id = this.templateId)
          const saveOrUpdate = () => {
            if (this.templateId) {
              return this.$interface.schedule.updateTemplateInfoApi(params)
            } else {
              return this.$interface.schedule.saveTemplateInfoApi(params)
            }
          }
          saveOrUpdate()
            .then(({ data: res }) => {
              this.saveLoading = false
              if (res.code !== 0) {
                return this.$message.error(res.msg)
              }
              this.$emit('updateListData')
              this.closeDialog()
              this.$message.success(res.msg)
            })
            .catch(() => { this.saveLoading = false })
        })
        .catch(() => { })
    },
    openDialog (type, id) {
      this.dialogType = type
      this.dialogStatus = true
      if (id) {
        this.getTemplateInfo(id)
      }
    },
    closeDialog () {
      this.dialogStatus = false
      this.closeBefore()
    },
    verifyNameAndTimezone () {
      return this.$refs['template-form'].validate()
    },
    closeBefore () {
      this.templateForm.templateName = null
      this.templateId = null
      this.scheduleData = [
        {
          'dayOfWeek': 'MONDAY',
          'beginTime': '',
          'endTime': '',
          'sort': 1
        },
        {
          'dayOfWeek': 'TUESDAY',
          'beginTime': '',
          'endTime': '',
          'sort': 2
        },
        {
          'dayOfWeek': 'WEDNESDAY',
          'beginTime': '',
          'endTime': '',
          'sort': 3
        },
        {
          'dayOfWeek': 'THURSDAY',
          'beginTime': '',
          'endTime': '',
          'sort': 4
        },
        {
          'dayOfWeek': 'FRIDAY',
          'beginTime': '',
          'endTime': '',
          'sort': 5
        },
        {
          'dayOfWeek': 'SATURDAY',
          'beginTime': '',
          'endTime': '',
          'sort': 6
        },
        {
          'dayOfWeek': 'SUNDAY',
          'beginTime': '',
          'endTime': '',
          'sort': 7
        }
      ]
      Object.assign(this.$data, this.$options.data())
    }
  }
}
</script>

<style scoped>
</style>
